﻿#region Copyright 2012 by Roger Knapp, Licensed under the Apache License, Version 2.0
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#endregion
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace CsProjectProjector
{
    public static class Extensions
    {
        public static XElement ElementByName(this XElement element, string localname)
        {
            return element.Elements().FirstOrDefault(e => e.Name.LocalName == localname);
        }

        public static IEnumerable<XElement> ElementsByName(this XElement element, string localname)
        {
            return element.Elements().Where(e => e.Name.LocalName == localname);
        }

        public static XAttribute AttributeByName(this XElement element, string localname)
        {
            return element.Attributes().FirstOrDefault(a => a.Name.LocalName == localname);
        }

        public static bool HasAttributeByName(this XElement element, string localname)
        {
            return null != element.Attributes().FirstOrDefault(a => a.Name.LocalName == localname);
        }

        public static string FirstElementName(this XElement element)
        {
            return element.Elements().Select(e => e.Name.LocalName).FirstOrDefault();
        }

        public static int IndexOf(this XElement element, XElement child)
        {
            return element.Elements().ToList().IndexOf(child);
        }

        public static void InsertAt(this XElement element, int index, XElement item)
        {
            if (index <= 0)
            {
                element.AddFirst(item);
            }
            else
            {
                var after = element.Elements().Skip(index - 1).FirstOrDefault();
                if (after != null)
                    after.AddAfterSelf(item);
                else
                    element.Add(item);
            }
        }
    }
}
